package treetool

import (
	"go-admin-auth/httpapi/dtoex"
	"strings"
)

type MenuTreeNode struct {
	dtoex.TMenuEx
	Child []*MenuTreeNode `json:"child"`
}

type menuTree struct {
	MenuList []dtoex.TMenuEx
	Tree     *MenuTreeNode
}

func initTree(tr *MenuTreeNode, menuList []dtoex.TMenuEx) {
	// 把菜单中等于tree.id的都取出来
	for _, v := range menuList {
		if v.ParentId == tr.Id {
			subTreeNode := &MenuTreeNode{TMenuEx: v}
			tr.Child = append(tr.Child, subTreeNode)
		}
	}

	for _, subTree := range tr.Child {
		initTree(subTree, menuList)
	}
}

func menuSelectOptionList(s *[]dtoex.TMenuEx, tr *MenuTreeNode, level int) {
	if level != -1 {
		prefixStr := strings.Repeat(" ", level*6)
		prefixStr += "└"
		tr.Name = prefixStr + tr.Name
		*s = append(*s, tr.TMenuEx)
	}

	for _, v := range tr.Child {
		menuSelectOptionList(s, v, level+1)
	}
}

func textTree(s *[]dtoex.TMenuEx, tr *MenuTreeNode, level int) {
	if tr.Id != 0 {
		prefixStr := ""
		tr.Name = prefixStr + tr.Name
		*s = append(*s, tr.TMenuEx)
	}

	for _, v := range tr.Child {
		textTree(s, v, level+1)
	}
}

func NewMenuTree(menuList []dtoex.TMenuEx, treeRootId int) *menuTree {
	tTree := &MenuTreeNode{}
	tTree.Id = treeRootId

	initTree(tTree, menuList)

	mTree := &menuTree{MenuList: menuList, Tree: tTree}
	return mTree
}

func (m *menuTree) GetTree() *MenuTreeNode {
	return m.Tree
}

func (m *menuTree) GetSelectOptions() []dtoex.TMenuEx {
	optionList := make([]dtoex.TMenuEx, 0, len(m.MenuList))
	menuSelectOptionList(&optionList, m.Tree, -1)
	return optionList
}

func (m *menuTree) GetTextTree() string {
	treeMenuList := make([]dtoex.TMenuEx, 0, len(m.MenuList))
	textTree(&treeMenuList, m.Tree, 0)

	var text1 string
	for _, v := range treeMenuList {
		text1 += v.Name + "\n"
	}

	return text1
}
